package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.CheckException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.vo.EmployeeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5DigestAsHex.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return employee;
    }

    @Override
    public void create(EmployeeDTO employeeDTO) {
        // 1. 参数的校验和判断
        String username = employeeDTO.getUsername();
        if (!StringUtils.hasText(username) || username.length() < 3 || username.length() > 20) {
            throw new CheckException("账号输入不符，请输入3-20个字符");
        }
        Employee employeeQuery = new Employee();
        employeeQuery.setUsername(username);
        Integer count = employeeMapper.selectCount(employeeQuery);
        if (count > 0) {
            throw new CheckException("账号重复，请调整");
        }
        // 2. 业务代码的编写（增删改查）
        Employee employee = new Employee();
        // 相同类型和名字的属性进行copy
        BeanUtils.copyProperties(employeeDTO, employee);
        // 默认密码需要加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5DigestAsHex);
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1. 参数校验
        int page = Objects.isNull(employeePageQueryDTO.getPage()) ? 1 : employeePageQueryDTO.getPage();
        int pageSize = Objects.isNull(employeePageQueryDTO.getPageSize()) ? 10 : employeePageQueryDTO.getPageSize();
        // 2. 业务 分页查询（分页插件）
        PageHelper.startPage(page, pageSize);
        // 原始查询
        Employee employeeQuery = new Employee();
        employeeQuery.setName(employeePageQueryDTO.getName());
        List<Employee> employeeList = employeeMapper.selectList(employeeQuery);
        Page<Employee> employeePage = (Page<Employee>) employeeList;
        // 3. 返回值的封装
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeePage.getTotal());
        pageResult.setRecords(employeePage.getResult());
        return pageResult;
    }

    @Override
    public void enableOrDisable(Long id, Integer status) {
        // 1. 直接更新
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.updateById(employee);
    }

    @Override
    public EmployeeVo infoById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(employee, employeeVo);
        return employeeVo;
    }

    @Override
    public void modifyById(EmployeeDTO employeeDTO) {
        // 1. 参数的校验
        String username = employeeDTO.getUsername();
        if (!StringUtils.hasText(username) || username.length() < 3 || username.length() > 20) {
            throw new CheckException("账号输入不符，请输入3-20个字符");
        }
        Employee employeeQuery = new Employee();
        employeeQuery.setUsername(username);
        employeeQuery.setId(employeeDTO.getId());
        Integer count = employeeMapper.selectCount(employeeQuery);
        if (count > 0) {
            throw new CheckException("账号重复，请调整");
        }
        // 更新  AOP 前置  注解（创建注解 - 新增和更新  建两个注解）
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setId(employeeDTO.getId());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);
    }

}
